package fr.futsal.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import fr.futsal.dao.EquipeDAOImpl;
import fr.futsal.domaine.Equipe;

/**
 * Servlet implementation class EnregistrementEquipe
 */
@WebServlet("/EnregistrementEquipe.html")
public class EnregistrementEquipeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Resource(name="jdbc/futsal")
	private DataSource futsalDS;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.getRequestDispatcher("/EnregistrementEquipe.jsp").forward(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		Connection connection = null;
		try {
			connection = futsalDS.getConnection();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}

		
		String nomDeLequipe = request.getParameter("nomEquipe");
		
		List<Equipe> listeEquipe = (List<Equipe>) request.getServletContext().getAttribute("sodomie");
		
		if(listeEquipe == null)
			 listeEquipe = new ArrayList<Equipe>();
		
		Equipe newEquipe = new Equipe();
		newEquipe.setNameEquipe(nomDeLequipe);		
		
		EquipeDAOImpl ajoutEquipe = new EquipeDAOImpl(connection);
		
		ajoutEquipe.enregistrerEquipe(newEquipe);
		
		request.getServletContext().setAttribute("sodomie",listeEquipe);
		
		response.sendRedirect("Equipes.html");
	}

}
